package com.xuwang.service.impl;

import com.xuwang.Util.DateTimeUtils;
import com.xuwang.Util.JWTutil;
import com.xuwang.Util.RandomNumberUtil;
import com.xuwang.mapper.*;
import com.xuwang.pojo.Additive;
import com.xuwang.pojo.FoodRelation;
import com.xuwang.pojo.Inventory;
import com.xuwang.pojo.Production;
import com.xuwang.vo.InventorySelectVO;
import com.xuwang.vo.ProductionVO;
import com.xuwang.vo.VO;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 生产表(Production)表服务实现类
 *
 * @author abaaba
 * @since 2021-09-17 09:43:37
 * @version 1.0
 */
@Service("productionService")
public class ProductionServiceImpl {
    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private AdditiveMapper additiveMapper;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private FoodRelationMapper foodRelationMapper;
    @Resource
    private RawMaterialMapper rawMaterialMapper;
    @Resource
    private FoodMapper foodMapper;




    public Map<String, Object> selectAddUse( int index, int page,
                                             String batchNo,String foodName,String beginTime,String endTime,String additiveName,Double number,String companyName) {
        // 获取当前表中的总记录
        int tableCount=0;
        index = (index - 1) * page;
        tableCount = this.productionMapper.selectAddUseForCount(batchNo,foodName,beginTime,endTime,additiveName,number,companyName);
        int pageCount = (tableCount - 1) / page + 1;
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "查询成功");
        map.put("pageCount", pageCount);  // 当前总数
        map.put("count", tableCount);     // 总条数.
        map.put("data", this.productionMapper.selectAddUse(index,page,batchNo,foodName,beginTime,endTime,additiveName,number,companyName));
        return map;
    }
    /**
     * 查询所有数据
     * @return  返回所有数据
     */
    public Map<String, Object> selectAll() {
        Map<String, Object> map = new HashMap<>();
        // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", this.productionMapper.selectAll());
        return map;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public Map<String, Object> selectById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败

        Integer type = productionMapper.selectTypeById(id);
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", this.productionMapper.selectById(id,type));
        return map;
    }

    /**
     * 查询分页数据
     *
     * @param index 查询起始位置
     * @return 对象列表
     */
    public Map<String, Object> selectForPageZF(int index, int page,
                                             Integer productionType, String matchName, String Company, String batchNo, String beginTime, String endTime, Integer warranty, String isDelete) {
        // 获取当前表中的总记录
        int tableCount=0;
        index = (index - 1) * page;
        tableCount = this.productionMapper.selectForCount(productionType,matchName,Company,batchNo,beginTime,endTime,warranty,isDelete);
        int pageCount = (tableCount - 1) / page + 1;
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "查询成功");
        map.put("pageCount", pageCount);  // 当前总数
        map.put("count", tableCount);     // 总条数
        map.put("data", this.productionMapper.selectForPage(index, page,productionType,matchName,Company,batchNo,beginTime,endTime,warranty,isDelete));
        return map;
    }
    /**
     * 查询分页数据
     *
     * @param index 查询起始位置
     * @return 对象列表
     */
    public Map<String, Object> selectForPageQY(int index, int page,
                                               Integer productionType, String matchName, String batchNo, String beginTime, String endTime, Integer warranty, String isDelete,
                                               HttpServletRequest request) {
        // 获取当前表中的总记录
        String token = request.getHeader("Authorization");
        String userName = JWTutil.getUserName(token);
        //生产类型需要查询！！！！！！
//        String userName="菜品人";
//        if (productionType==1){
//            userName="原料人";
//        }else if (productionType==2){
//            userName="添加剂人";
//        }else if (productionType==3){
//            userName="菜品人";
//        }
        int tableCount = this.productionMapper.selectForCount(productionType,matchName,
                additiveMapper.selectCompanyNameByUsername(userName),
                batchNo,beginTime,endTime,warranty,isDelete);
        // 总页码计算   (总条数 - 1) / 每页显示条数  + 1
        // (100 - 1) / 10 + 1 = 10        (101 - 1) / 10 + 1 = 11      (99 - 1) / 10 + 1 = 10
        int pageCount = (tableCount - 1) / page + 1;
        // 计算每页开始的下标值
        index = (index - 1) * page;
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "查询成功");
        map.put("pageCount", pageCount);  // 当前总数
        map.put("count", tableCount);     // 总条数
        map.put("data", this.productionMapper.selectForPage(index, page,productionType,matchName,
                additiveMapper.selectCompanyNameByUsername(userName),batchNo,beginTime,endTime,warranty,isDelete));
        return map;
    }



    public Map<String, Object> selectProduction(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userName = JWTutil.getUserName(token);
        Map<String, Object> map = new HashMap<>();
//        String userName="原料人";
        int companyId ;
                String adminType = additiveMapper.selectCompanyTypeByUsername(userName);
        if ("原料".equals(adminType)){
             companyId = additiveMapper.selectCompanyIdByUsername(userName);
             map.put("code",200);
            List<VO> data = rawMaterialMapper.selectAll01(companyId);
            for (VO vo : data) {
                vo.setType(1);
            }
            map.put("data",data);
        }else if("添加剂".equals(adminType)){
             companyId = additiveMapper.selectCompanyIdByUsername(userName);
            map.put("code",200);
            List<VO> data = additiveMapper.selectAll01(companyId);
            for (VO vo : data) {
                vo.setType(2);
            }
            map.put("data",data);

        }else{
            map.put("code",200);
            List<VO> data = foodMapper.selectAllFood01();
            for (VO vo : data) {
                vo.setType(3);
            }
            map.put("data",data);
        }
        return map;
    }

    /**
     * 新增数据
     *
     * @param productionVO 实例对象
     * @return 实例对象
     */
    public Map<String, Object> insert(ProductionVO productionVO, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userName = JWTutil.getUserName(token);
        String tishi = "";
        Map<String, Object> map = new HashMap<>();
//        String userName=null;
        String zj="";
        if (productionVO.getType()==1){
//            userName="原料人";
            zj="yl";
        }else if (productionVO.getType()==2){
//            userName="添加剂人";
            zj="tjj";
        }else if (productionVO.getType()==3){
//            userName="菜品人";
            zj="cp";
            //根据菜品id查询需要的添加剂和原料，名称和数量。1

            int companyId = additiveMapper.selectCompanyIdByUsername(userName);
            List<FoodRelation> foodRelations = foodRelationMapper.selectNameAndNumberByFoodId(productionVO.getMatchId());
            for (FoodRelation relation : foodRelations) {
                if ( inventoryMapper.selectByNameAndCompanyId(relation.getFoodRelationMatchName(), companyId)==0||
                        relation.getFoodRelationMatchNumber() * productionVO.getNumber()
                        > inventoryMapper.selectCountNumberByNameAndCompanyId(relation.getFoodRelationMatchName(), companyId)) {
                   tishi+=relation.getFoodRelationMatchName()+"库存不足！";
                }
            }
            if (tishi.equals("")){
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                String s = DateTimeUtils.getTodayChar17() + zj + RandomNumberUtil.createRandomNumber(10);


                //插入库存
                this.inventoryMapper.insert(productionVO.getType(), s, productionVO.getMatchName(), productionVO.getNumber(), companyId);
                //减少库存
//                for (FoodRelation relation : foodRelations) {
//                    this.inventoryMapper.updateNumberByNoAndCompanyId( inventoryMapper.selectCountNumberByNameAndCompanyId(relation.getFoodRelationMatchName(), companyId)-relation.getFoodRelationMatchNumber() * productionVO.getNumber(),
//                            , s, productionVO.getMatchName(),companyId);
//                }
                for (FoodRelation relation : foodRelations) {
                    double total = relation.getFoodRelationMatchNumber() * productionVO.getNumber();
                        List<InventorySelectVO> inventorySelectVOS = inventoryMapper.selectMyCompanyInventoryByName(relation.getFoodRelationMatchName(), companyId);
                        for (InventorySelectVO inventorySelectVO : inventorySelectVOS) {
                            if (inventorySelectVO.getNumber()>total){
                                inventoryMapper.updateNumberByNoAndCompanyId(inventorySelectVO.getNumber()-total,
                                        inventorySelectVO.getBatchNo(),companyId);
                                total=0.0;
                                break;
                            }else {
                                total-=inventorySelectVO.getNumber();
                                inventoryMapper.updateNumberByNoAndCompanyId(0.0,
                                        inventorySelectVO.getBatchNo(),companyId);
                            }
                        }
                }
                    this.productionMapper.insert(productionVO.getType(),
                        productionVO.getMatchId(),
                        companyId,
                        s,
                        productionVO.getNumber(),
                        productionVO.getSpecification(),
                        Timestamp.valueOf(format), 0, productionVO.getMatchName(), productionVO.getWarranty()
                );
            map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
            map.put("msg", "新增成功");
            }else {
                map.put("code", 201);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
                map.put("msg", tishi);
            }

        }
        if (productionVO.getType()!=3) {
            int i = additiveMapper.selectCompanyIdByUsername(userName);

            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            String s = DateTimeUtils.getTodayChar17() + zj + RandomNumberUtil.createRandomNumber(10);


            //插入库存
            this.inventoryMapper.insert(productionVO.getType(), s, productionVO.getMatchName(), productionVO.getNumber(), i);


            this.productionMapper.insert(productionVO.getType(),
                    productionVO.getMatchId(),
                    i,
                    s,
                    productionVO.getNumber(),
                    productionVO.getSpecification(),
                    Timestamp.valueOf(format), 0, productionVO.getMatchName(), productionVO.getWarranty()
            );

            map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
            map.put("msg", "新增成功");
        }
        return map;
    }

    /**
     * 更改
     *
     * @param production 实例对象
     * @return 实例对象
     */
    public Map<String, Object> updateById(Production production,HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        String userName = JWTutil.getUserName(token);
//        String userName=null;
//        if (production.getProductionType()==1){
//            userName="原料人";
//        }else if (production.getProductionType()==2){
//            userName="添加剂人";
//        }else if (production.getProductionType()==3){
//            userName="菜品人";
//        }
        productionMapper.updateIsDeleteById(production.getId().toString(),1);//删除更改前的数据
        this.productionMapper.insert(production.getProductionType(),
                production.getMatchId(),
                additiveMapper.selectCompanyIdByUsername(userName),
                production.getBatchNo(),
                production.getProductionNumber(),
                production.getSpecification(),
                Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())),0,production.getMatchName()
                ,production.getWarranty()
        );
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "更新成功");
        return map;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public Map<String, Object> deleteById(String id) {
        this.productionMapper.deleteById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "删除成功");
        return map;
    }


    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public Map<String, Object> updateIsDeleteById(String id) {
        this.productionMapper.updateIsDeleteById(id,1);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "删除成功");
        return map;
    }

    /**
     * 批量删除多条数据
     *
     * @param ids 批量主键
     * @return 单条数据
     */
    public Map<String, Object> updateIsDeleteByIds(String ids) {
        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {
            this.productionMapper.updateIsDeleteById(split[i],1);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);   // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("msg", "删除多条成功");
        return map;
    }

    public Map<String, Object> selectBatchByMyCompany(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userName = JWTutil.getUserName(token);
//       String userName="菜品人";
        int companyId = additiveMapper.selectCompanyIdByUsername(userName);
        Map<String, Object> map = new HashMap<>();
        // 前端端分离时，前端人员会首先判断code值是否满足200，如果不是200，则提醒用户失败
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", this.productionMapper.selectBatchByMyCompany(companyId));
        return map;
    }
}